<?php

/**
 *https://yu04z8h3n0.apifox.cn/api-242611048
 * 接口文档实现
 */

namespace Api\Http\Controllers;


use AllowDynamicProperties;
use Api\Service\FilmService;
use Api\traits\ApiResponse;

use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Modules\Film\Models\FilmOrder;
use Modules\Member\Models\MembersFilmProfit;


/**
 * @group 用户模块
 *
 * @subgroup 用户管理
 * @subgroupDescription CatchAdmin 后台用户管理
 *
 */
#[AllowDynamicProperties] class FilmController extends Controller
{
    use ApiResponse;

    public function __construct(
        protected readonly FilmService $service
    )
    {
        $level = config('level');
        $this->percent = isset($level['film_percent']) ?(string)$level['film_percent'] : '0.89';
        $this->quick = isset($level['quick_percent']) ?(string)$level['quick_percent'] : '0.95';

    }

    public function index(Request $request): Response
    {
        $status = $request->get('status', '');
        $search = $request->get('search', '');
        $query = FilmOrder::where('user_id', $this->getLoginUserId());
        if (is_numeric($status)) {
            $query->where('status', $status);
        }
        if (!empty($search)) {
            $query->where(function ($query) use ($search) {
                $query->where('cinema_name', 'like', '%' . $search . '%')->orWhere('show_name', 'like', '%' . $search . '%');
            });
        }
        $list = $query->where('is_paid',1)->orderBy('id', 'desc')->paginate(10)->toArray();
        foreach ($list['data'] as $key => $item) {
            $showInfo = json_decode($item['show_info'], true);
            $cinemaInfo = json_decode($item['cinema_info'], true);
            foreach ($showInfo as $name => $value) {
                $list['data'][$key][$name] = $value;
            }
            foreach ($cinemaInfo as $name2 => $value2) {
                $list['data'][$key][$name2] = $value2;
            }
        }
        return $this->data($list);
    }

    /**
     * @param string $id
     * @return Response
     */
    public function show(string $id)
    {
        $info = FilmOrder::find($id);
        return $this->data($info->toArray());
    }

    /**
     * @param Request $request
     * @return mixed
     * @throws GuzzleException
     * 影院列表
     */
    public function getCinemas(Request $request)
    {

        $data = $request->post();
        $result = $this->service->getCinemas($data);
        if ($result == false) {
            return $this->fail('请求超时');
        }
        $list = $result['result'];
        if (empty($list)) {
            $return['success'] = false;
            $return['code'] = 200;
            $return['result'] = [];
            return json($return);
        }
        foreach ($list as $k => $v) {
            $list[$k]['paidPrice'] = bcmul((string)$list[$k]['price'], $this->percent, 2);
            $list[$k]['quickPrice'] = bcmul((string)$list[$k]['price'], $this->quick, 2);
        }
        $result['result'] = $list;
        return $result;
    }

    /**
     * @return mixed
     * @throws GuzzleException
     * 获取城市列表
     */
    public function getCityList()
    {
        $result = $this->service->getCityList();
        return $result;
    }

    /**
     * @param Request $request
     * @return mixed
     * @throws GuzzleException
     * 获取影院排期信息
     */
    public function getCinemaSchedule(Request $request)
    {
        $data = $request->post();
        $result = $this->service->getCinemaSchedule($data);
        $filmInfo = $result['result'];
        if (empty($filmInfo)) {
            $return['success'] = false;
            $return['code'] = 200;
            $return['result'] = [];
            return json($return);
        }
        foreach ($filmInfo as $k => $v) {
            $originPrice = $v['price'];
            $filmInfo[$k]['truePrice'] = $v['price'];
            $filmInfo[$k]['paidPrice'] = bcmul((string)$originPrice, $this->percent, 2);
            $filmInfo[$k]['quickPrice'] = bcmul((string)$originPrice, $this->quick, 2);
        }
        ksort($filmInfo);
        $result['result'] = $filmInfo;

        return $result;
    }

    public function sliderList(Request $request)
    {
        $hotList = $this->service->getHotMovies($request->post());
        $result = $hotList['result'];
        $slider = [];
        foreach ($result as $k => $v) {
            $slider[] = $v['pic'];
        }
        $hotList['result'] = $slider;
        return $hotList;
    }

    public function cinemaDetail(Request $request)
    {
        $data = $request->post();
        return $this->service->cinemaDetail($data);
    }

    public function filmRegions(Request $request)
    {
        $data = $request->post();
        return $this->service->filmRegions($data);
    }

    public function checkTicketPrices(Request $request)
    {
        $data = $request->post();
        return $this->service->checkTicketPrices($data);
    }

    /**
     * @param Request $request
     * @return Response|mixed
     * 获取热门电影列表
     */
    public function getHotMovies(Request $request)
    {
        $data = $request->post();
        if(empty($data['ci'])){
            $return['success'] = false;
            $return['code'] = 200;
            $return['result'] = [];
            $return['message'] = '城市id不能为空';
            return json($return);
        }
        $search = $data['search'] ?? '';
        $result = $this->service->getHotMovies($data);

        if (!empty($search)) {
            $movieList = $result['result'];
            $newList = [];
            foreach ($movieList as $movie) {
                if (str_contains($movie['name'], $search)) {
                    $newList[] = $movie;
                }
            }
            $result['result'] = $newList;
        }
        return $result;

    }

    /**
     * @param Request $request
     * @return mixed
     * @throws GuzzleException
     * 获取即将上映电影列表
     */
    public function getInComingMovies(Request $request)
    {
        $data = $request->post();
        return $this->service->getInComingMovies($data);
    }


    public function getMovieScheduleDetail(Request $request)
    {
        $data = $request->post();
        return $this->service->getMovieScheduleDetail($data);
    }

    /**
     * @param Request $request
     * @return mixed
     * 获取座位信息
     */
    public function getMovieSeats(Request $request)
    {
        $data = $request->post();
        $mode = $data['mode'] ?? 0;
        $list = $this->service->getMovieSeats($data);
        if ($list['success'] == false) {
            $return['success'] = false;
            $return['code'] = 200;
            $return['result'] = [];
            return json($return);
        }
        $seatList = $list['result']['movieFilmSeatData'];
        foreach ($seatList as $k => $v) {
            $seatList[$k]['truePrice'] = $v['price'];
            if ($v['status'] != 'E') {
                    $seatList[$k]['paidPrice'] = bcmul((string)$v['price'], $this->percent, 2);
                    $seatList[$k]['quickPrice'] = bcmul((string)$v['price'], $this->quick, 2);
                }
            }
        $list['result']['movieFilmSeatData'] = $seatList;
        return $list;
    }

    public function moviePlayDate(Request $request)
    {
        $data = $request->post();
        return $this->service->moviePlayDate($data);
    }

    public function createOrder(Request $request)
    {

        $data = $request->post();
        $orderSn = uniqid();
        $data['orderId'] = $orderSn;
        $data['outId'] = $orderSn;
        $data['param']['testModel'] = 0;  //测试
        $result = $this->service->preOrder($data);
        if ($result['code'] == 200 && $result['success']) {
            $showInfoJson = $result['result']['showInfo'];
            $showInfoArr = json_decode($showInfoJson, true);
            $stopTime = $showInfoArr['stopsellTime'];
            if(Carbon::now()->gt($stopTime)){
                return $this->fail('该场次已停售,请选择其他场次,谢谢配合');
            }
            foreach ($data as $k => $v) {
                $newKey = Str::snake($k);
                if ($newKey == "buy_seats") {
                    $seat_json = json_encode($v);
                    $newParam[$newKey] = $seat_json;
                } else {
                    $newParam[$newKey] = $v;
                }
            }
            $seatInfo = json_decode($result['result']['seats'], true);
            $statArr = array_column($seatInfo, 'seatNo');
            $order = new FilmOrder();
            $newParam['order_sn'] = $orderSn;
            $newParam['user_id'] = $this->getLoginUserId();
            $newParam['seats'] = implode(',', $statArr);
            $newParam['show_info'] = $result['result']['showInfo'];
            $newParam['cinema_info'] = $result['result']['cinemaInfo'];
            $newParam['buy_num'] = $result['result']['buyNum'];
            $original_price = bcdiv((string)$result['result']['salePrice'], 100, 2);  //原价
            $cost_price = bcmul((string)$result['result']['buyNum'],$original_price,2);   //成本价
            $newParam['original_price'] = $cost_price;  //原价
            $realPercent = bcmul($this->percent, (string)$result['result']['buyNum'], 2);
            $newParam['paid_price'] = bcmul($original_price, $realPercent, 2); //实际支付价格 *数量
//            $newParam['cost_price'] = $cost_price;  //成本价 *数量
            $res = $order->fill($newParam)->save();
            if ($res) {
                $result['order_sn'] = $orderSn;
                $wechat = new WechatController();
                $payInfo = $wechat->getFilmPayInfo($orderSn);
                return $payInfo;
            } else {
                return $this->fail('下单失败');
            }
        } else {
            return $this->fail($result['message']);
        }
    }

    public function test(Request $request)
    {
        $orderSn = $request->post('order_sn');
        $result = $this->service->createOrder($orderSn);
        return $result;
    }

    //电影票api回调
    public function callback(Request $request)
    {
        $result = $request->post();

        $outId = $result['outId'];
        $status = $result['status'];
        $orderInfo = FilmOrder::where('order_sn', $outId)->first();
        if ($status == 'DrawFinish') {
            $body = $result['body'];
            $body = json_decode($body, true, 512, JSON_UNESCAPED_UNICODE);
            if (isset($body['realSeat'])) {
                $orderInfo->seats = $body['realSeat'];
            }
            $orderInfo->cost_price = bcdiv((string)$result['platPayPrice'], '100', 2);//成本价格
            $tickInfo = $result['ticketsArr'];
            if (!empty($tickInfo)) {
                $ticketCodeArr = [];
                $ticketImgArr = [];
                foreach ($tickInfo as $v) {

                    $ticketCodeArr[] = $v['ticketInfo'];
                    $ticketImgArr[] = $v['ticketImg'];
                }
                $orderInfo->ticket_code = $ticketCodeArr;
                $orderInfo->ticket_img = $ticketImgArr;
            }

            $orderInfo->status = 1;
            $orderInfo->save();
        } else {
            $orderInfo->status = 2;  //出票失败
            $orderInfo->save();
            $wechat = new WechatController();
            $wechat->refundFilmOrder($orderInfo->order_sn);  //电影票退款
        }
        $return = [];
        $return['success'] = true;
        $return['message'] = '';
        $return['result'] = new \stdClass();
        $return['code'] = 200;
        return json($return);
    }

    /**
     * @return Response
     * 收益列表
     */
    public function profitList()
    {
        $list = MembersFilmProfit::with(['user','order'])->where('user_id', $this->getLoginUserId())->get();
        return $this->data($list->toArray());
    }
}
